package com.leyou.auth.controller;

import com.leyou.auth.service.AuthService;
import com.leyou.common.auth.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @PostMapping("/login")
    public ResponseEntity<Void> login(
            @RequestParam("username")String username,
            @RequestParam("password")String password,
            HttpServletResponse response
            ){

        this.authService.login(username,password,response);

        return ResponseEntity.ok().build();
    }

    //@CookieValue 专门从cookie中取值，传入具体的cookie名称
    @GetMapping("/verify")
    public ResponseEntity<UserInfo> verify(HttpServletResponse response,HttpServletRequest request){
        return ResponseEntity.ok(this.authService.verify(response,request));
    }

    @PostMapping("/logout")
    public ResponseEntity<Void> logout(HttpServletResponse response, HttpServletRequest request){

        this.authService.logout(response,request);

        return ResponseEntity.ok().build();
    }


    /**
     * 微服务认证并申请令牌
     * 为什么微服务，返回string，但是用户不返回，string，
     * 用户服务时，保存token是交由cookie保存，此时微服务中没有cookie，所以干脆不管了，直接返回token，
     * @param id 服务id
     * @param secret 密码
     * @return 无
     */
    @GetMapping("/authorization")
    public ResponseEntity<String> authorize(@RequestParam("id") Long id, @RequestParam("secret") String secret) {
        return ResponseEntity.ok(authService.authenticate(id, secret));
    }
}
